package models

type PermissionMenu struct {
	ID        int               `gorm:"primary_key" json:"id"`
	ParentId  int               `json:"parent_id"`
	Path      string            `json:"path"`
	Hidden    int               `json:"hidden"`
	Component string            `json:"component"`
	Redirect  string            `json:"redirect"`
	Name      string            `json:"name"`
	Title     string            `json:"title"`
	Icon      string            `json:"icon"`
	ApiUrl    string            `json:"api_url"`
	CreatedAt string            `json:"created_at"`
	UpdatedAt string            `json:"updated_at"`
	Children  []*PermissionMenu `json:"children,omitempty"`
}

type PermissionMenuRole struct {
	PermissionId int `json:"permission_id"`
	RoleId       int `json:"role_id"`
}

func (p PermissionMenu) TableName() string {
	return "permissions_menu"
}

func GetPermissionMenuAll() []*PermissionMenu{
	var data []*PermissionMenu
	_ = DB.Table("permissions_menu").Find(&data).Error
	list := MenuBuildDate(data)
	m := MenuMakeTreeCore(0, list)
	return m
}

//todo 获取角色对应的所有权限菜单
func GetRolePermissionMenuList(role_id int) []*PermissionMenu {
	var data []*PermissionMenu
	_ = DB.Table("permission_menu_role as t1").
		Joins("left join permission_menu as on t1.permission_menu_id = t2.id").
		Where("t1.role_id=?", role_id).
		Select("t2.*").
		Find(&data).
		Error
	list := MenuBuildDate(data)
	m := MenuMakeTreeCore(0, list)
	return m
}

//todo 添加权限
func MenuBuildDate(list []*PermissionMenu) (map[int]map[int]*PermissionMenu) {
	data := make(map[int]map[int]*PermissionMenu)
	for _, v := range list {
		id := v.ID
		fid := v.ParentId
		if _, ok := data[fid]; !ok {
			data[fid] = make(map[int]*PermissionMenu)
		}
		data[fid][id] = v
	}
	return data
}

func MenuMakeTreeCore(index int, data map[int]map[int]*PermissionMenu) []*PermissionMenu {
	tmp := make([]*PermissionMenu, 0)
	for id, item := range data[index] {

		if data[id] != nil {
			item.Children = MenuMakeTreeCore(id, data)
		}
		tmp = append(tmp, item)
	}
	return tmp
}

//todo 修改权限

//todo 查看单个

//todo 删除
